﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using StockFinder.Model;
using System.IO;

namespace StockFinder.HistoricalPriceAnalysers
{
    public class DonchainHistoricalPriceAnalyser
    {
        public List<HistoricPriceAnalyserResult> AnalysePrices(List<DailyPrice> prices, decimal maxDrawdown)
        {
            var results = new List<HistoricPriceAnalyserResult>();

            var orderedPrices = prices.OrderBy(p => p.PriceDate).ToArray();               

            int priceCount = orderedPrices.Count();
            DailyPrice lastHigh = orderedPrices[0];
            DailyPrice startPrice = orderedPrices[0];

            decimal numberOfShares = 0m;
            decimal account = 100000m;
            decimal percentRisk = 1m;
            bool hasPosition = false;

            numberOfShares = Math.Floor( account / startPrice.AdjustedClose );

            for (int i = 1; i < priceCount; i++)
            {
                var currentPrice = orderedPrices[i];

                if (!hasPosition)
                {
                    
                }

                //new high price?
                if (currentPrice.AdjustedClose > lastHigh.AdjustedClose)
                {
                    lastHigh = currentPrice;
                }
               
                //are we at drawdown?
                var drawdown = ((lastHigh.AdjustedClose - currentPrice.AdjustedClose) / lastHigh.AdjustedClose) * 100;

                var moveFromInitial = ((lastHigh.AdjustedClose - startPrice.AdjustedClose) / startPrice.AdjustedClose) * 100;

                if (drawdown >= maxDrawdown)
                {                    
                    results.Add(new HistoricPriceAnalyserResult(){
                        LastPriceDate = startPrice.PriceDate,
                        DepthFromHigh = moveFromInitial,
                        BaseDepth = drawdown,
                        BaseLength = (currentPrice.PriceDate - startPrice.PriceDate).Days
                    });

                    //start again from now
                    startPrice = currentPrice;
                    lastHigh = currentPrice;
                }
            }


            return results;
        }
    }
}
